import app, { xlsxCfgNames } from "./app";
import { bag } from "./model/bag/bag";
import server_mail from "./server_mail";
import { face_prop_item, mail_item, rank_item, rank_type } from "./shared/interface";
import manage_user from "./master/model/manage/manage_user";
import { _Cls_Att } from "./model/fight/body/att/_Att";
import server_rank from "./server_rank";
import { template } from "./shared/master/MsgAction";
import { prop_base } from "./model/bag/prop_base";
import { EntrustTask } from "./master/model/task/EntrustTask";
import db from "./model/db/db";

class god {
    sellBag = new bag();
    shop_equip = new bag();
    shop_skill = new bag();
    nextAddTime = Date.now()
    private oneMoreMap: Map<number, { str: string, auth: string }> = new Map()
    rank_tickList: any[] = [];
    constructor() {
        setInterval(() => {
            this._rankTickUpload();
        }, 100)
        setInterval(() => {
            this.loadOneMore();
        }, 60000)
    }
    async oneMore() {
        if (this.oneMoreMap.size == 0) {
            await this.loadOneMore();
        }
        // 将 Map 转换为数组
        let entries = Array.from(this.oneMoreMap.entries());
        let [randomKey, randomValue] = entries[app.random(0, entries.length)];
        this.oneMoreMap.delete(randomKey);
        return randomValue;
    }
    private async loadOneMore() {
        if (this.oneMoreMap.size > 300) {
            return;
        }
        let res = await db.sql(`SELECT * FROM oneMore ORDER BY RAND() LIMIT 100;`, [])
        for (let i = 0; i < res.length; i++) {
            const element = res[i];
            this.oneMoreMap.set(element.id, { str: element.str, auth: element.auth })
        }
    }
    getDNA_info(leve: number) {
        let cfg = app.xlsxCfgMap.get(xlsxCfgNames.基因锁表) as Map<string, any>;
        let nowInfo = cfg.get(leve.toString());
        if (!nowInfo) {
            debugger;
            return {};
        }
        return nowInfo;
    }
    getRandomItem(score: number, from: string) {
        const table = app.xlsxCfgMap.get(xlsxCfgNames.商店配置) as Map<string, any>
        const list = [...table.values()];
        const idx = app.randomWeight(list);
        const item = list[idx];

        const _prop = app.createCfgItem(item.sell_id, score, from)
        _prop.value = Math.ceil(app.random(_prop.value * 0.8, _prop.value * 1.5))
        return _prop
    }
    getRandomItem_v2(score: number, from: string, table: Map<string, any>, aline?) {
        const list = [...table.values()];

        const idx = app.randomWeight(list);
        const item = list[idx];

        const _prop = app.createCfgItem(item.sell_id, score, from)
        if (_prop.value < score && aline) {
            let cont = Math.floor((score - _prop.value) / _prop.value);
            if(!cont){
                cont = 1;
            }
            _prop.cont_change(cont)
        }
        return _prop
    }
    getRandomItem_v2Tname(score: number, from: string, table: string, aline?) {
        let _table = app.xlsxCfgMap.get(table) as Map<string, any>
        return this.getRandomItem_v2(score, from, _table, aline)
    }
    getRandomItems(score: number, from: string, tableName: string, aline?,all?) {
        let table = app.xlsxCfgMap.get(tableName) as Map<string, any>
        let giveValue = 0;

        let needValue = score;
        let locaBag = new bag();
        while (needValue > giveValue) {
            let start = app.generateRandom(1, needValue - giveValue);
            if(all){
                start = needValue - giveValue;
            }
            const _randomItem = this.getRandomItem_v2(start, from, table, aline);
            giveValue += Math.ceil(_randomItem.value * _randomItem.num);
            locaBag.add(_randomItem);
        }
        return locaBag.items as prop_base[];
    }
    getRandomItem_score(score: number, from: string) {
        let needValue = score;
        let giveValue = 0;
        let locaBag = new bag();
        while (needValue > giveValue) {
            const _randomItem = this.getRandomItem(app.random(1, needValue - giveValue), from);
            giveValue += _randomItem.value;
            locaBag.add(_randomItem);
        }
        return locaBag.items;
    }
    async rank_tick(data: rank_item) {
        this.rank_tickList.push(data)
    }
    private async _rankTickUpload() {
        if (this.rank_tickList.length == 0) {
            return;
        }
        let data = this.rank_tickList.shift();
        await server_rank.c_http.callApi('Update', { data: data })
    }
    check() {
        if (this.nextAddTime > Date.now()) {
            return;
        }
        // 设置下一个添加时间为下一个整点的时间
        this.nextAddTime = Date.now() + app.random(1, 10) * 1000 * 60;
        this.sellBag.sort()
        this.shop_equip.sort()
        this.shop_skill.sort()
        if (this.sellBag.size() < 500) {
            for (let index = 0; index < 50; index++) {
                const item = this.getRandomItem(app.random(1, 1000), '主神商店')
                item.value = app.random(item.value * 2, item.value * 5)
                this.sellBag.add(item)
            }
        }
        while (this.shop_equip.size() < 10) {
            let item = this.getRandomItem_v2Tname(app.random(1, 1000), '主神商店', 'Shop_equip');
            item.value = app.random(item.value*50, item.value*100)
            this.shop_equip.add(item)
        }
        while (this.shop_skill.size() < 10) {
            let item = this.getRandomItem_v2Tname(app.random(1, 1000), '主神商店', 'Shop_skill');
            item.value = app.random(item.value*50, item.value*100)
            this.shop_skill.add(item)
        }
    }

    /**
     * 额外百分百加成
     * @param add 
     * @returns 
     */
    getRandomTitleValue(add: number = 0) {
        let att = new _Cls_Att();
        for (const key in att) {
            if (key.startsWith('_')) {
                continue;
            }
            att[key] = app.generateRandom(0, 1000 + add * 1000) / 100;
        }
        return att;
    }
    /**
     * 获取一个随机的角色形象
     */
    getRamdomStyle() {
        // let cfg = app.xlsxCfgMap.get(xlsxCfgNames.天赋表)?.get(talent_id) as any;
        // let styles = cfg.styles;
        // let idx = styles[app.random(0, this.getServerCfgItem('style_body').b)]
        return app.random(1, this.getServerCfgItem('style_body').b).toString()
    }
    getServerCfgItem(k: string) {
        const table = app.xlsxCfgMap.get(xlsxCfgNames.服务器配置) as Map<string, any>;
        const cfg = table.get(k);
        return cfg
    }
    /**
     * 
     * @param from 
     * @param to_uuid 
     * @param title 
     * @param content 
     * @param annexs 
     */
    async send(from: { uuid: string, name: string }, to_uuid: string, title: string, content: string, annexs: face_prop_item[]) {
        const locaTag = manage_user.locaHas(to_uuid);
        const mailItem: mail_item = {
            create: Date.now(),
            from: {
                uuid: from.uuid,
                name: from.name
            },
            to: {
                uuid: to_uuid
            },
            title: title,
            content: content,
            annexs: annexs,
        }

        if (locaTag) {
            locaTag.sendMsg(template.default, `你有来自${mailItem.from.name}的新邮件请注意查收~`)
            locaTag.mail.push(mailItem)
        } else {
            let req = await server_mail.c_http.callApi('Send', { data: mailItem })
        }
    }
}
export default new god()